﻿using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Read.Api.RBACServices.IServices;
using B.T.BasicData.Read.Api.RBACServices.Services;
using Microsoft.EntityFrameworkCore;
using NLog.Web;
using System.Reflection;
using Yitter.IdGenerator;
using B.T.BasicData.Read.Api.DTOs;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using B.T.BasicData.Read.Api.Common;
using B.T.BasicData.Read.Api.Common.ICommon;

namespace B.T.BasicData.Read.Api.Extensions
{
    /// <summary>
    /// 拓展类方法  静态类   静态方法  this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {

            // Add services to the container.

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //显示中文
            builder.Services.AddSwaggerGen(x =>
            {
                var file = Path.Combine(AppContext.BaseDirectory + "B.T.BasicData.Read.Api.xml");
                x.IncludeXmlComments(file, true);

                // 显示 授权信息
                x.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                x.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
            });

            //注册EFCore上下文
            builder.Services.AddDbContext<MyDbContext>(x =>
            {
                x.UseMySql(builder.Configuration["ConnectionStrings:Conn"],ServerVersion.AutoDetect(builder.Configuration["ConnectionStrings:Conn"]), action =>
                {
                    //配置EFCore的重试策略
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,//最大重试次数
                        maxRetryDelay: TimeSpan.FromSeconds(60),//每次重试间隔时间 最大延迟
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();//启用敏感数据日志记录，使与调试，但在生产环境中应谨慎使用以避免泄露敏感信息

                //x.UseMySql(builder.Configuration.GetConnectionString("Conn"), new MySqlServerVersion("5.7.22"));

                //配置日志记录
                x.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddFilter(
                    category: DbLoggerCategory.Database.Name,//类别
                    level: LogLevel.Information//控制台日志
                    ).AddConsole()));
            });

            /// JWTGV地方恨不得蝴蝶夫人代发不打你打放哪到哪么

            //注入
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            builder.Services.AddScoped<IRoleServices, RoleServices>();
            builder.Services.AddScoped<IUserServices, UserServices>();
            builder.Services.AddScoped<ILoginServices, LoginServices>();
            builder.Services.AddScoped<IPermissionsServices, PermissionsServices>();

            builder.Services.AddScoped<IIdentivyService, IdentivyService>();
            //AutoMapper
            builder.Services.AddAutoMapper(typeof(mapperingProfile));
            //中介者
            builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //builder.Services.AddScoped<IServices,Services>();
            //区分大小写
            builder.Services.AddControllersWithViews().AddJsonOptions(p => p.JsonSerializerOptions.PropertyNamingPolicy = null);
            //注入日志、
            builder.Host.UseNLog();
            //雪花Id
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1));

            //注册http  获取请求上下文
            builder.Services.AddHttpContextAccessor();

            //JWT
            var jwtSettings = builder.Configuration.GetSection("JWtSettings").Get<JWtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SigningKey);
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtSettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtSettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });


            return builder;
        }



        // public static IServiceCollection AddDbContextAccessor(this IServiceCollection services,string connectionString,bool enableSqlLog)
        // {

        // }
    }
}
